package com.artron.mediaartron.data.net;

import com.artron.mediaartron.data.entity.LoginData;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.bind.TreeTypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-10-17.
 */

class SpecialTypeAdapterFactory implements TypeAdapterFactory {

    private final Gson mJsonParser;
    private final List<Class> mTypeList = new ArrayList<>();

    SpecialTypeAdapterFactory(){
        mJsonParser = new GsonBuilder().create();
        mTypeList.add(LoginData.class);
    }

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        JsonDeserializer<T> deserializer = null;
        Class<? super T> rawType = type.getRawType();
        for (Class clazz : mTypeList) {
            if (rawType.equals(clazz)) {
                deserializer = new SpecialAdapter<>();
                break;
            }
        }
        return new TreeTypeAdapter<>(null, deserializer, gson, type, this);
    }

    private class SpecialAdapter<T> implements JsonDeserializer<T>{

        @Override
        public T deserialize(JsonElement json, Type typeOfT,
                             JsonDeserializationContext context) throws JsonParseException {
            try {
                return mJsonParser.fromJson(json, typeOfT);
            } catch (Exception e) {
                return null;
            }
        }
    }

    /**
     *
     private final Gson mJsonParser;

     private List<TypeAdapterFactory> mTypeAdapterFactories = new ArrayList<>();
     private static SpecialTypeAdapterFactory sFactory = new SpecialTypeAdapterFactory();

     private SpecialTypeAdapterFactory(){
     mJsonParser = new GsonBuilder().create();
     //添加特殊的判断类型
     mTypeAdapterFactories.add(TreeTypeAdapter.newTypeHierarchyFactory(LoginData.class,
     new SpecialAdapter<LoginData>()));
     }
     public static SpecialTypeAdapterFactory newInstance(){
     return sFactory;
     }

     List<TypeAdapterFactory> getTypeAdapterFactories() {
     return mTypeAdapterFactories;
     }

     private class SpecialAdapter<T> implements JsonDeserializer<T>{

    @Override
    public T deserialize(JsonElement json, Type typeOfT,
    JsonDeserializationContext context) throws JsonParseException {
    try {
    return mJsonParser.fromJson(json, typeOfT);
    } catch (Exception e) {
    return null;
    }
    }
    }
     */

}
